package com.ilovepostcard;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.widget.RemoteViews;

import com.ilovepostcard.utils.Constants;

public class GetNewVersionService extends IntentService {

	private String apkPath;

	private Handler handler;
	
	public GetNewVersionService() {
		super("download service");
		handler = new Handler();
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		String url = intent.getStringExtra("url");
		Log.d(Constants.TAG, "url=" + url);
		String dir = Environment.getExternalStorageDirectory()
				+ "/ilovepostcard/";
		if (!(new File(dir).exists())) {
			new File(dir).mkdirs();
		}

		apkPath = dir + "Postcard_new.apk";

		HttpGet httpGet = new HttpGet(url);
		HttpClient httpClient = new DefaultHttpClient();
		
		handler.post(new Runnable() {
            
            @Override
            public void run() {
                notificationUpdate(MainActivity.ACTION_DOWNLOADING, 0);
            }
        });
		
		
		try {
			HttpResponse response = httpClient.execute(httpGet);

			if (response.getStatusLine().getStatusCode() == 200) {
				File file = new File(apkPath);
				if(file.exists()){
					file.delete();
				}
				
				HttpEntity entity = response.getEntity();
				//Long contentLength = entity.getContentLength();
				FileOutputStream fos = new FileOutputStream(file);
				InputStream inStream = entity.getContent();
				final long ALL = entity.getContentLength();
				byte[] buffer = new byte[1<<13];
				int len = 0;
				long all = 0;
				final int step = 10;
				int nextNotifyProgress = step;
				while ((len = inStream.read(buffer)) > 0) {
					fos.write(buffer, 0, len);
					all += len;
					int progress = (int)(all * 100 / ALL);
					if (progress >= nextNotifyProgress) {
					    final int notify = nextNotifyProgress;
					    nextNotifyProgress += step;
    					handler.post(new Runnable() {
    			            
    			            @Override
    			            public void run() {
    			                notificationUpdate(MainActivity.ACTION_DOWNLOADING, notify);
    			            }
    			        });
					}
				}
				fos.close();
				inStream.close();
				
				handler.post(new Runnable() {
		            
		            @Override
		            public void run() {
		                notificationUpdate(MainActivity.ACTION_DOWNLOAD_SUCCESS, 0);
		            }
		        });
				
				Log.d(Constants.TAG,"download finished---");
				
				Uri uri = Uri.fromFile( file ); 
				Intent mIntent = new Intent(Intent. ACTION_VIEW );
				mIntent.setDataAndType(uri, "application/vnd.android.package-archive"); 
				mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				
				startActivity(mIntent); 
			}
			else
			{
				notificationUpdate(MainActivity.ACTION_DOWNLOAD_FAIL, 0);
			}
		}  catch(Exception exception ){
		    handler.post(new Runnable() {
	            
	            @Override
	            public void run() {
	                notificationUpdate(MainActivity.ACTION_DOWNLOAD_FAIL, 0);
	            }
	        });
		}

	}

	
	private void notificationUpdate(String action, int progress) {
	    Intent intent = new Intent();
	    intent.setAction(action);
	    intent.putExtra("progress", progress);
	    sendBroadcast(intent);
	}
}
